//
//  ViewController.swift
//  Weibo_SwiftDemo
//
//  Created by gjh on 2020/12/12.
//

import UIKit
import SVProgressHUD

class JHMainTabBarController: UITabBarController {

    // 定时器
    private var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        navigationController?.navigationBar.barTintColor = Spec.color.tint
        setupChildViewControllers()
        setupComposeButton()
        setupTimer()
        
        // 设置tabber监听代理
        delegate = self
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: JHUserShouldLoginNotification), object: nil)
    }
    // MARK: - 生命周期
    deinit {
        // 销毁时钟
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    // portrait  : 竖屏 landscape  :横屏
    // 使用代码控制设备的方向,好处,可以在需要横屏的时候,单独处理
    // 设置支持的方向之后,当前的控制器及其自控制器都会保持这个方向
    // 如果播放视频,通常是通过 modal 展现的
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        .portrait
    }
    
    // MARK: - 通知的监听方法
    @objc private func userLogin(n: Notification) {
        print("用户的登录通知\(n)")
        
        // 判断n.object 是否有值,如果有值 -> token 过期,提示用户重新登录
        var when = DispatchTime.now()
        if n.object != nil {
            SVProgressHUD.setDefaultMaskType(.gradient) // 渐变
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时,需要重新登录")
            // 增加延迟时间
            when = DispatchTime.now() + 2
        }
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            // 展现登录控制器  -通常会和UINavigationController连用,方便返回
            let loginVC = UINavigationController(rootViewController: JHOAuthViewController())
            self.present(loginVC, animated: true, completion: nil)
        }
    }
    // MARK: - 按钮的监听方法
    // private 能够保证方法私有 仅在当前对象被访问
    // @objc 允许这个函数在'运行时'通过 OC 的消息机制访问
    @objc private func composeClick() {
        print("撰写微博")
        
        // 测试方向的旋转
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.yellow
        let nav = UINavigationController(rootViewController: vc)
        nav.modalPresentationStyle = UIModalPresentationStyle(rawValue: 0)!;
        present(nav, animated: true, completion: nil)
        
    }
    // MARK: - 私有控件
    // 撰写按钮
    private lazy var composeButton: UIButton = {
        let addButton = UIButton()
        addButton.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        addButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        return addButton
    }()
}
// MARK: - UITabBarControllerDelegate
extension JHMainTabBarController: UITabBarControllerDelegate {
    
    
    /// 将要选择 tabberItem
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到 \(viewController)")
        
        // 1\获取控制器在数组中的索引
        let idx = children.firstIndex(of: viewController)
        if selectedIndex == 0 && selectedIndex == idx {
            print("点击首页返回顶部")
            // 让表格滚动到顶部
            let vc = children[0] as! JHHomeViewController
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            // 刷新数据,增加延迟,保证表格先滚动到顶部,再刷新
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                vc.loadData()                
            }
        }
        // 如果点到 uiviewcontroller 就不切换
        return !viewController.isMember(of: UIViewController.self)
    }
}

// MARK: - 时钟相关的方法
extension JHMainTabBarController {
    // 定义时钟
    private func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    /// 时钟触发方法
    @objc private func updateTimer() {
        
        // 登录之后再进行定时刷新
        if !JHNetworkManager.instance.userLogon {
            return
        }
        JHNetworkManager.instance.unreadCount { (count) in
            print("检测到\(count)条新微博")
            // 设置 首页 tabbarItem的 badgeNumber
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            // 设置 app 的 badgenum 从 iOS8 之后,需要用户的授权才能显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

// MARK: - 设置界面
extension JHMainTabBarController {
    
    private func setupComposeButton() {
        tabBar.addSubview(composeButton)
        // 计算按钮的宽度
        let count = CGFloat(viewControllers!.count)
        // 因为在加号图片的旁边一点点的地方容易切换到空白处,在这里-1,就可以扩大加号图片的范围,但是这个方法并不是最好的,应该使用上面的 shoud...代理方法,做出是否跳转的判断
        let w = tabBar.bounds.width / count  // 之前是通过 - 1 处理
        // 这个方法很牛逼  CGRectInset 正数向内缩进,负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeClick), for: .touchUpInside)
    }
    // 设置所有子控制器
    private func setupChildViewControllers() {
        
        // 获取沙盒 json 路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let json = (docDir as NSString).appendingPathComponent("/main.json")
        // 加载data
        var data = NSData(contentsOfFile: json)
        
        // 判断 data是否有内容,如果没有,说明本地沙盒没有文件
        if data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        // 从 bundle 加载配置的 json
        // 1\ 路径  2\ 加载 NSData 3\ 反序列化转换成数组
        // 推荐 try? 如果解析成功,就有值,否则为 nil
        /* 处理异常,能够接收到错误,并能输出错误
        do {
            let array = try JSONSerialization.jsonObject(with: data! as Data, options: [])
        } catch {
            print(error)
        } */
        guard let VCArray = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: Any]]
        else { return }
        
//        let VCArray: [[String: Any]] = [
//            ["className": "JHHomeViewController", "title": "首页", "imageName": "home", "visitorInfo": ["imageName": "", "message": "关注一些人,回这里看看有什么惊喜"]
//            ],
//            ["className": "JHMessageViewController", "title": "消息", "imageName": "message_center", "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知"]
//            ],
//            ["className": "UIViewController"],
//            ["className": "JHDiscoverViewController", "title": "发现", "imageName": "discover", "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后,最新,最热微博尽在掌握,不会再与实事潮流擦肩而过"]
//            ],
//            ["className": "JHMineViewController", "title": "我的", "imageName": "profile", "visitorInfo": ["imageName": "visitordiscover_image_profile", "message": "登录后,你的微博,相册,个人资料会显示在这里,展示给别人"]
//            ]
//        ]
//
//        // 测试数据格式是否正确--转换成 plist 文件更加直观
////        (VCArray as NSArray).write(toFile: "/Users/kevin/Desktop/demo.plist", atomically: true)
//
//        // 数组 -> json 序列化
//        let data = try! JSONSerialization.data(withJSONObject: VCArray, options: [.prettyPrinted])
//        (data as NSData).write(toFile: "/Users/kevin/Desktop/demo.json", atomically: true)
        var arrayM = [UIViewController]()
        
        for dict in VCArray {
            arrayM.append(controller(dict: dict))
        }
        viewControllers = arrayM
    }
    
    private func controller(dict: [String: Any]) -> UIViewController {
        guard let className = dict["className"] as? String,
              let title = dict["title"] as? String,
              let imageName = dict["imageName"] as? String,
              let cls = NSClassFromString(Bundle.main.namespace + "." + className) as? JHBaseViewController.Type,
              let visitorDic = dict["visitorInfo"] as? [String: String]
        
        else {
            return UIViewController()
        }
        // 创建 VC
        let VC = cls.init()
        VC.title = title
        // 设置控制器的访客信息字典
        VC.visitorViewDict = visitorDic
        
        VC.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        VC.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal) // 渲染
        VC.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.orange], for: .highlighted)
        // 设置字体
//        VC.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)], for: UIControl.State.init(rawValue: 0)) //.normal
//        let nav = JHNavigationController(rootViewController: VC)
        return VC
    }
}
